
(function($, win, doc){
	
	/**
	 *  默认值：/seeyon
	 */
	var appBasePath = (function(){
		
		var path = location.pathname;
		
		return path.substring(0, path.indexOf('/', 1));
	})();
	
	function getCtpParentWindow(_win) {
	    
		_win = _win || window;
	    
	    for (var i = 0; i < 20; i++) {
	    	
	        if (typeof _win.isCtpTop != "undefined" && _win.isCtpTop) {
	        	
	            return _win;
	            
	        } else {
	        	
	            if (_win == window.top) {
	            	
	                break;
	            }
	            
	            _win = _win.parent;
	        }
	    }
	}

	function getCtpTop() {
		
	    try {
	    	
	        var _win = getCtpParentWindow(window);
	        
	        if (_win) {
	            return _win;
	        } else {
	            return top;
	        }
	        
	    } catch (err) {
	        return top;
	    }
	}
	
	
	
	var app = new Vue({
		el: '#app',
		data: {
			style:{
				selectedIndex: 'first',
				selection: win.dialogArguments.selection
			},
			basic:{
				mark: win.dialogArguments.mark,
				recordSize: 0,
				hasTree: false
			},
			paginationData:{
				page: 1,
				per_page_size: 20,
				total_row_size: 0
			},
			config: null,
			queryTreeKeyword: null,
			queryTreeValue: null,
			queryTree: {
				props: { label: 'n', children: 's'},
				data: null
			},
			queryForm:{
				code: null,
				name: null
			},
			queryParams: [{
				key: 'name',
				name: '名称',
				inKey: null,
				type: 'string',
				defaultValue: null
			},{
				key: 'code',
				name: '编码',
				inKey: null,
				type: 'string',
				defaultValue: null
			}],
			queryFParams:[],
			dataTitle:[{
				key: 'name',
				name: '姓名',
				width: 300,
				display: true,
				lock: false,
				example: '...'
			},{
				key: 'code',
				name: '编码',
				width: 300,
				display: true,
				lock: false,
				example: '...'
			}],
			dataList:[{
				name: '...',
				code: '...'
			},{
				name: '...',
				code: '...'
			}],
			recordDataList: [],
			recordDataIndex: null
		},
		methods:{
			init: function(){
				
				this.loadConifg();
				
			},
			loadConifg: function(){

				var _this = this;
				
				$.http.get({
					url: (appBasePath + '/snail/formext/getdata.do?method=getConfig'),
					header: {'Accept': 'application/json'},
					data:{mark: this.basic.mark},
					onsuccess: function(result, status, xhr){
						
						var data = null;
						
						if(200 == result.code){
							
							data = result.data;
							
						}else{
							getCtpTop().$.alert(result.message);
						}
						
						if(null != data){

							_this.config = data;
														
							(function(config){
								
								var queryForm = {};
								var queryParams = [];
								var queryFParams = [];
								
								for(var i=0,len=config.length; i<len; i++){
									
									queryForm[config[i].key] = null;
									
									if($.isBlank(config[i].inKey)){
									
										queryParams.push(config[i]);
									}else{
										queryFParams.push(config[i]);
									}
								}
								
								_this.queryForm = queryForm;
								_this.queryParams = queryParams;
								_this.queryFParams = queryFParams;
							})(data.dataset['in']);
							
							_this.dataTitle = (function(config){
								
								for(var i=0,len=config.length; i<len; i++){
									
									if(true == config[i].lock){
										
										config[i].lock = 'left';
									}
								}

								return config;
							})(data.dataset['out']);
							
							_this.onTree();
							_this.onQuery();
							
						}else{
							getCtpTop().$.alert('获取配置信息为空！');
						}
						
					},
					onerror: function(responseText, status, xhr){
						console.log(responseText);
					}
				});
			},
			onTree: function(){

				var _this = this;
				
				$.http.get({
					url: (appBasePath + '/snail/formext/getdata.do?method=getTreeData'),
					header: {'Accept': 'application/json'},
					data:{mark: this.basic.mark},
					onsuccess: function(result, status, xhr){
						
						if(200 == result.code){
							
							if(result.data){
								
								_this.queryTree.data = result.data;
								_this.basic.hasTree = true;
							}
							
						}else{
							getCtpTop().$.alert(result.message);
						}						
					},
					onerror: function(responseText, status, xhr){
						console.log(responseText);
					}
				});
				
			},
			onQuery: function(){
				
				var _this = this;
				
		    	var progress = null;
		    	
		    	try{
		    		
		    		progress = getCtpTop().$.progressBar();
			    	
					$.http.post({
						url: (appBasePath + '/snail/formext/getdata.do?method=getData&mark=' + this.basic.mark),
						header: {
							'Content-Type': 'application/json', 'Accept': 'application/json',
							'pagination.page': this.paginationData.page, 
							'pagination.per_page_size': this.paginationData.per_page_size
						},
						data: (function(data, config, config2, formData, recordId){
							
							var key = null;
							var value = null;
							var param = {};
							
							if('groovy' == _this.config.dataset.script.type 
									|| 'http' == _this.config.dataset.script.type){
								
								param['pagination'] = {
									page: _this.paginationData.page,
									per_page_size: _this.paginationData.per_page_size
								};
							}
							
							for(var i=0,len=config.length; i<len; i++){
								
								key = config[i].key;
								value = data[key];
								
								if('like' == config[i].type){
									param[key] = ('%' + (!$.isBlank(value) ? value : (config[i].defaultValue || '')) + '%');
								}else{
									param[key] = (!$.isBlank(value) ? value : config[i].defaultValue);
								}
							}
							
							for(var i=0,len=config2.length; i<len; i++){
								
								key = config2[i].key;
								value = (function(key, type, data, recordId){
									
									key = key.substring(key.indexOf('.') + 1);
									
									for(var tableName in data.formdata.formmains){
										
										var fieldInfo = data.formdata.formmains[tableName][key];
										
										if(fieldInfo){
											return fieldInfo.value;
										}
									}
									
									if(recordId){
										
										for(var tableName in data.formdata.formsons){
											
											for(var i=0,len=data.formdata.formsons[tableName].records.length; i<len; i++){

												if(!data.formdata.formsons[tableName].records[i]){
													continue;
												}
												
												if(recordId == data.formdata.formsons[tableName].records[i].recordId){
													
													var fieldInfo = data.formdata.formsons[tableName].records[i].lists[key];
													
													if(fieldInfo){
														return fieldInfo.value;
													}
												}
											}
										}
									}
									
									return null;
								})(config2[i].inKey, config2[i].type, formData, recordId);
								
								if('like' == config2[i].type){
									param[key] = ('%' + (!$.isBlank(value) ? value : (config2[i].defaultValue || '')) + '%');
								}else{
									param[key] = (!$.isBlank(value) ? value : (config2[i].defaultValue || ''));
								}
							}
							
							if(_this.queryTreeValue){
								
								for(var name in _this.queryTreeValue){
									
									if('s' == name){
										continue;
									}
									
									param['__getdata_tree_' + name] = _this.queryTreeValue[name];
								}
							}
							
							return param;
						})(this.queryForm, this.queryParams, this.queryFParams, win.dialogArguments.data, win.dialogArguments.recordId),
						onsuccess: function(result, status, xhr){
							
							if(200 == result.code){
								
								if(!$.isBlank(result.data) && $.isArray(result.data)){
									
									var unqiue = [];
									var out = _this.config.dataset.out;
									
									for(var i=0,len=out.length; i<len; i++){
										
										if(out[i]){
											unqiue.push(out[i].key);
										}
									}
									
									var generateUnqiue = null;
									
									if(0 == unqiue.length){
										
										generateUnqiue = function(row, index){

											if(null == row){
												return;
											}
											
											row['__SNAIL_UNQIUE_KEY__'] = new String(((_this.paginationData.page - 1) * _this.paginationData.per_page_size) + index);
											row['__SNAIL_INDEX__'] = index;
										}
										
									}else{
										
										generateUnqiue = function(row, index){
											
											if(null == row){
												return;
											}
											
											var strUnqiue = '';
											
											for(var i=0,len=unqiue.length; i<len; i++){
												
												strUnqiue += row[unqiue[i]];
											}
											
											row['__SNAIL_UNQIUE_KEY__'] = strUnqiue;
											row['__SNAIL_INDEX__'] = index;
										}
									}
									
									var newData = [];
									
									var len = result.data.length;
									
									if(len > _this.paginationData.per_page_size){
										
										len = _this.paginationData.per_page_size;
										
										console.log('GetDATA返回的数据长度超过分页值（' + _this.paginationData.per_page_size + '），实际长度为' + result.data.length);
									}
									
									for(var i=0; i<len; i++){
										
										generateUnqiue(result.data[i], i);
										
										newData.push(result.data[i]);
									}
									
									_this.dataList = newData;
									
								}else{
									_this.dataList = null;
								}
								
							} else {
								
								_this.dataList = null;
								
								getCtpTop().$.alert(result.message);
							}
							
						},
						onerror: function(responseText, status, xhr){
							
							_this.dataList = null;
							
							getCtpTop().$.alert(responseText);
						},
						oncomplete: function(responseText, status, xhr){
							
							var totalRowSize = xhr.getResponseHeader('pagination.total_row_size');
							
							if('groovy' == _this.config.dataset.script.type 
									|| 'http' == _this.config.dataset.script.type){
								
								_this.paginationData.total_row_size = (null != _this.dataList ? _this.dataList.length : 0);
							}
							
							_this.paginationData.total_row_size = win.parseInt(totalRowSize ? totalRowSize : _this.paginationData.total_row_size);

							progress && progress.close();
						}
					});
		    		
		    	}catch(err){
		    		
		    		progress && progress.close();
		    		
		    		getCtpTop().$.alert(err);
		    	}
		    	
			},
			onReset: function(){

				this.queryTreeValue = null;
				
				this.queryForm = (function(data){
					
					var newData = {};
					
					for(var name in data){
						newData[name] = null;
					}
					
					return newData;
				})(this.queryForm);

				this.onQuery();
			},
			onTabsChange: function(tab, event){
				
				if('first' == tab.name){
					
					this.doDataListLayout();
				}
			},
			onSelectData: function(selection){
				
				/**
				 * 测试：
				 * console.log('当前被选数据', selection);
				 */ 
				
				if(selection){
					
					// 添加
					if(this.recordDataList){
						
						var rlen = this.recordDataList.length;
						var exist = false;
						
						for(var i=0,len=selection.length; i<len; i++){
							
							exist = false;
							
							for(var j=0; j<rlen; j++){
								
								if(selection[i]['__SNAIL_UNQIUE_KEY__'] == this.recordDataList[j]['__SNAIL_UNQIUE_KEY__']){
									
									exist = true;
									break;
								}
							}
							
							if(exist){
								continue;
							}
							
							this.recordDataList.push($.deepcopy(selection[i]));
						}
						
						// 取消 (删除当前页取消选择的数据)
						rlen = selection.length;
						
						for(var i=0,len=this.dataList.length; i<len; i++){
							
							exist = false;
							
							for(var j=0; j<rlen; j++){
								
								if(this.dataList[i]['__SNAIL_UNQIUE_KEY__'] == selection[j]['__SNAIL_UNQIUE_KEY__']){
									
									exist = true;
									break;
								}
							}
							
							if(exist){
								continue;
							}
							
							for(var j=0,jlen=this.recordDataList.length; j<jlen; j++){
								
								if(this.dataList[i]['__SNAIL_UNQIUE_KEY__'] == this.recordDataList[j]['__SNAIL_UNQIUE_KEY__']){
									
									this.recordDataList.splice(j, 1);
									
									jlen--;
									j--;
								}
							}
						}
						
					}else{
						this.recordDataList = $.deepcopy(selection);
					}	
										
				}else{
					
					if(this.recordDataList){
						
						// 取消 (删除当前页取消选择的数据【全部】)
						for(var i=0,len=this.dataList.length; i<len; i++){
							
							for(var j=0,jlen=this.recordDataList.length; j<jlen; j++){
								
								if(this.dataList[i]['__SNAIL_UNQIUE_KEY__'] == this.recordDataList[j]['__SNAIL_UNQIUE_KEY__']){
									
									this.recordDataList.splice(j, 1);
									
									jlen--;
									j--;
								}
							}
						}
					}
				}
				
				if(this.recordDataList){
					this.basic.recordSize = this.recordDataList.length;
				}else{
					this.basic.recordSize = 0;
				}
				
			},
			onSelectRowData: function(row, column, ev){

				/**
				 * 测试：
				 * console.log('当前行数据', row);
				 */ 
				
				if(this.style.selection){  // 多选
					
					this.$refs.dataList.toggleRowSelection(row);
					
				}else{  // 单选
					
					this.recordDataList = [$.deepcopy(row)];

					this.basic.recordSize = 1;
				
					this.recordDataIndex = row['__SNAIL_INDEX__'];
				}
			},
			onDBLSelectRowData: function(row, column, ev){
				
				this.recordDataList = [$.deepcopy(row)];

				this.basic.recordSize = 1;
				
				this.onBackfillForm();
			},
			onQueryTree: function(value, data) {
				
				if (!value) {
					return true;
				}
				
				return (-1 != data.n.indexOf(value)) || (data.c && -1 != data.c.indexOf(value));
			},
			onCurrentChangeQueryTree: function(data, node){
				
				this.queryTreeValue = data;

				this.onQuery();
			},
			onPaginationSizeChange: function(val){
				
				this.paginationData.per_page_size = val;
				
				this.onQuery();
			},
			onPaginationChange: function(val){
				
				this.paginationData.page = val;
				
				this.onQuery();
			},
			onDeleteRecord: function(index, row){
				
				var newData = [];
				
				for(var i=0,len=this.recordDataList.length; i<len; i++){
					
					if(index == i){
						continue;
					}
					
					newData.push(this.recordDataList[i]);
				}
				
				this.recordDataList = newData;
				this.basic.recordSize = newData.length;
			},
			onClose: function(){
				
				win.dialogArguments.dialog.close();
			},
			/**
			 * 回填数据
			 */
			onBackfillForm: function(){
				
				win.dialogArguments.dialog.backfillForm({
					data: this.recordDataList,
					config: this.config
				});
			},
			/* 解决 Element-UI table fixed 错位问题 */
			doDataListLayout: function(){
				
				var _this = this;
				
				this.$nextTick(function(){
					_this.$refs.dataList.doLayout();
				});
			}
		},
		created: function(){
			this.init();
		},
		watch:{
			queryTreeKeyword: function(val, oldVal){
				
				this.$refs.queryTree.filter(val);
				
			},
			dataList: function(val, oldVal){
				this.doDataListLayout();
			}
		}
	});
	
	
	win['OK'] = function(){
		
		if(!app.recordDataList || 0 == app.recordDataList.length){
			
			return {
				code: 500,
				message: '至少选择一条数据！',
				data: null
			};
		}
		
		return {
			code: 200,
			message: '成功',
			data: {
				data: app.recordDataList,
				config: app.config
			}
		};
	}
	
	/**
	 * 解决Google浏览器回车造成刷新问题 
	 */
	doc.onkeydown = function (ev) {
		
		ev.stopPropagation();
		
		if (ev.keyCode == 13) {
			return false;
		}
		
	};

})(Snail, window, document);